<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        ref="searchForm"
        :model="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item prop="org" :label="'单位名称'">
          <Select v-model="searchForm.org" clearable @on-change="searchValueSet">
            <Option v-for="item in projectOrgList" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="name" :label="'项目名称'">
          <Select v-model="searchForm.name" clearable @on-change="searchValueSet">
            <Option v-for="item in projectNameList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="sortType" :label="'排序方式'">
          <Select v-model="searchForm.sortType" clearable @on-change="searchValueSet">
            <Option v-for="item in sortTypeList" :value="item.key" :key="item.key">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <!-- <RPButton optType="search" @click="searchValueSet()" /> -->
          <RPButton optType="reset" @click="resetAndSearchValueSet()" />
          <RPButton optType="search" text="导出" @click="exportExcel()" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <div style="margin:10px;overflow-x: auto;">
      <hot-table
        v-if="!loading"
        :readOnly="false"
        class="hot_table"
        ref="hotTableComponent"
        :data="formData"
        :settings="hotSettings"
      ></hot-table>
    </div>
  </div>
</template>

<script>
import { HotTable } from '@handsontable/vue'
import 'handsontable/dist/handsontable.full.css'
import 'handsontable/languages/zh-CN'
import dataApi from '@/api/formData'
import { aoaToExcel } from './utils'
import { mapState } from 'vuex'
export default {
  name: 'judgesSummary',
  components: { HotTable },
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    type: {
      type: Number,
      default: 0
    },
    stage: {
      type: Number,
      default: null
    },
    fromHistory: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isShared: false,
      treeData: [],
      loading: true,
      projectNameList: [],
      projectOrgList: [],
      searchForm: {
        org: '',
        name: '',
        sortType: 0
      },
      sortTypeList: [],
      sortType0List: [
        { key: 1, name: '按平均分升序' },
        { key: 2, name: '按平均分降序' }
      ],
      sortType1List: [
        { key: 1, name: '按总分升序' },
        { key: 2, name: '按总分降序' }
      ],
      formData: [],
      JudgesColHeaders: [],
      JudgesColumns: [],
      mergeCells: [],
      type1ColHeaders: ['项目名称', '推荐单位', '评分指标', '评委', '得分', '总分'],
      networkData: {}
    }
  },
  computed: {
    ...mapState(['orgList']),
    hotSettings() {
      return {
        //许可证
        licenseKey: 'ab3e4-1bee8-ed01c-4d94b-08cfe',
        rowHeaders: true,
        colHeaders: this.type === 0 ? this.JudgesColHeaders : this.type1ColHeaders,
        // width: '100%',
        wordWrap: true,
        mergeCells: this.mergeCells,
        columns:
          this.type === 0
            ? this.JudgesColumns
            : [
                {
                  data: 0,
                  readOnly: true,
                  headerClassName: 'header'
                },
                {
                  data: 1,
                  readOnly: true,
                  headerClassName: 'header'
                },
                {
                  data: 2,
                  readOnly: true,
                  headerClassName: 'header'
                },
                {
                  data: 3,
                  readOnly: true,
                  headerClassName: 'header'
                },
                {
                  data: 4,
                  readOnly: true,
                  headerClassName: 'header'
                },
                {
                  data: 5,
                  readOnly: true,
                  headerClassName: 'header'
                }
              ],
        height: 'auto',
        colWidths: 100,
        rowHeights: 40,
        //自动拉伸
        stretchH: 'all',
        language: 'zh-CN',
        className: 'htCenter htMiddle',
        filters: true, // 启用基本的筛选功能
        // columnSorting: true,
        autoWrapRow: true,
        // dropdownMenu: true,
        cell: [],
        //导出文件插件
        exportFile: true,
        //公式插件
        formulas: true,
        autoWrapCol: true
      }
    }
  },
  methods: {
    dealTreeData(orgData) {
      let data = JSON.parse(JSON.stringify(this.treeToFlat(orgData)))
      data.forEach(node => {
        node.checked = false
        node.title = node.orgName
      })
      data[0].children = []
      this.treeData = data
    },

    exportExcel() {
      const hotInstance = this.$refs.hotTableComponent.hotInstance
      if (hotInstance) {
        let fileName = this.row.formName + '-' + (this.type === 0 ? '评委维度' : '评分指标维度')
        let merge = JSON.parse(JSON.stringify(this.hotSettings.mergeCells))
        //添加头
        merge.forEach(item => {
          item.row = 1 + item.row
        })
        let sheetMerges = this.changeMergeCellsToSheet(merge)
        const header = hotInstance.getColHeader()
        const data = hotInstance.getData()
        aoaToExcel([header, ...data], sheetMerges, fileName)
      }
    },
    changeMergeCellsToSheet(mergeCells) {
      let merges = []
      mergeCells.forEach(item => {
        if (item.rowspan !== 1 || item.colspan !== 1) {
          let tmp = {
            s: {
              //s为开始
              c: item.col, //开始列
              r: item.row //可以看成开始行,实际是取值范围
            },
            e: {
              //e结束
              r: item.row + item.rowspan - 1, //结束列
              c: item.col + item.colspan - 1 //结束行
            }
          }
          merges.push(tmp)
        }
      })
      return merges
    },
    // 获取汇总数据
    async getData() {
      // todo--汇总的数据返回的不对
      this.sortTypeList = this.type == 0 ? this.sortType0List : this.sortType1List
      const res = await dataApi.getSummaryList({ formId: this.row.formId, stage: this.stage })
      this.networkData = res.data
      if (this.fromHistory) {
        //过滤当前评分阶段、当前评分对象
        this.networkData = this.networkData.filter(item => {
          const raw = JSON.parse(item.raw)
          return raw.stage == this.row.stage && this.row.evaluationTargetTitle == raw.evaluationTargetTitle
        })
        this.convertData(this.networkData)
      } else {
        //过滤当前评分阶段
        this.networkData = this.networkData.filter(item => {
          const raw = JSON.parse(item.raw)
          return raw.stage == this.row.stage
        })
        this.convertData(this.networkData)
      }
    },
    /**
     * 转换为项目数据
     */
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    shwoFriendly(num) {
      if (!num && num !== 0) {
        return '-'
      }
      return num
    },
    convertData(resData, isSearch, sortType) {
      // 按parentId 排序，方便合并
      resData.sort((a, b) => a.parentId.localeCompare(b.parentId))
      this.loading = true
      this.isShared = resData[0].isShared
      let leafs = []
      this.formData = []
      this.mergeCells = []
      if (this.type === 0) {
        // 评委维度
        let groups = []
        resData.forEach((item, index) => {
          //子单据，生成本单据的数据
          const raw = JSON.parse(item.raw)
          const projectName = raw.evaluationTargetTitle || '-'
          const org = this.treeData.find(item => item.orgCode == raw.evaluationTargetOrg) || {
            orgCode: '-',
            orgName: '-'
          }
          const orgName = org?.orgName || '-'
          if (!isSearch) {
            if (!this.projectNameList.includes(projectName)) {
              this.projectNameList.push(projectName)
            }
            if (!this.projectOrgList.includes(org)) {
              this.projectOrgList.push(org)
            }
          }
          let row = [projectName, orgName, raw.creator]
          let adjust = {}
          let data = []
          if (raw) {
            Object.keys(raw).forEach(key => {
              if (key.startsWith('fld')) {
                adjust = raw[key].adjust || { add: 0, minus: 0 }
                data = raw[key].data || []
              }
            })
          }
          leafs = data
            .filter(item => item.isRoot === false)
            .map(item => {
              return { id: item.id, label: item.indicatorName }
            })
          const leafsLabel = leafs.map(item => item.label)
          this.JudgesColHeaders = ['项目名称', '推荐单位', '评委', ...leafsLabel, '加分项', '减分项', '得分', '平均分']
          leafs.forEach(leaf => {
            data.forEach(item => {
              if (item.id === leaf.id) {
                row.push(this.shwoFriendly(item.scoreValue))
              }
            })
          })
          //加分项
          row.push(this.shwoFriendly(adjust.add))
          //减分项
          row.push(this.shwoFriendly(adjust.minus))
          row.push(this.shwoFriendly(raw.score))
          this.formData.push(row)
          const group = groups.find(group => group.projectName == projectName)
          if (group) {
            group.index.push(index)
            group.score.push(Number(raw.score))
          } else {
            groups.push({ projectName: projectName, index: [index], score: [Number(raw.score)] })
          }
        })
        //计算平均分
        groups.forEach(group => {
          let total = 0
          group.score.forEach(s => {
            total = total + s
          })
          if (this.isShared) {
            group.average = total
          } else {
            group.average = total / group.score.length
          }
          //添加平均分
          group.index.forEach(i => {
            this.formData[i].push(this.shwoFriendly(group.average.toFixed(2)))
          })
        })
        //按平均分排序
        if (sortType === 1) {
          //按平均分降序
          this.formData.sort((b, a) => b[a.length - 1] - a[a.length - 1])
        } else if (sortType === 2) {
          //按平均分升序
          this.formData.sort((a, b) => b[a.length - 1] - a[a.length - 1])
        }
        this.JudgesColumns = []
        for (let i = 0; i < this.JudgesColHeaders.length; i++) {
          // 遍历数组，对每个元素进行操作
          this.JudgesColumns.push({
            data: i,
            readOnly: true,
            headerClassName: 'header'
          })
        }
        //合并
        let last = ''
        let lastRow = 0
        const indexs = [0, 1, this.JudgesColHeaders.length - 1]
        for (let i = 0; i < this.formData.length; i++) {
          if (i == 0) {
            last = this.formData[i][0]
          } else if (i == this.formData.length - 1) {
            //最后一行
            if (last == this.formData[i][0]) {
              indexs.forEach(index => {
                this.mergeCells.push({
                  row: lastRow,
                  col: index,
                  rowspan: i - lastRow + 1,
                  colspan: 1
                })
              })
            }
          } else {
            if (last !== this.formData[i][0]) {
              last = this.formData[i][0]
              indexs.forEach(index => {
                this.mergeCells.push({
                  row: lastRow,
                  col: index,
                  rowspan: i - lastRow,
                  colspan: 1
                })
              })
              lastRow = i
            }
          }
        }
      } else {
        // 评分指标维度
        // 按总分排序
        if (sortType === 1) {
          //按总分降序
          resData.sort((b, a) => {
            return Number(JSON.parse(b.raw).score) - Number(JSON.parse(a.raw).score)
          })
        } else if (sortType === 2) {
          //按总分升序
          resData.sort((a, b) => {
            return Number(JSON.parse(b.raw).score) - Number(JSON.parse(a.raw).score)
          })
        }
        let start = 0
        resData.forEach(item => {
          //子单据，生成本单据的数据
          const raw = JSON.parse(item.raw)
          let info = raw
          const projectName = info.evaluationTargetTitle || '-'
          const org = this.treeData.find(item => item.orgCode == raw.evaluationTargetOrg) || {
            orgCode: '-',
            orgName: '-'
          }
          const orgName = org?.orgName || '-'
          if (!isSearch) {
            if (!this.projectNameList.includes(projectName)) {
              this.projectNameList.push(projectName)
            }
            if (!this.projectOrgList.includes(org)) {
              this.projectOrgList.push(org)
            }
          }
          let row = []
          let adjust = {}
          let data = []
          if (info) {
            Object.keys(info).forEach(key => {
              if (key.startsWith('fld')) {
                adjust = info[key].adjust || { add: 0, minus: 0 }
                data = info[key].data || []
              }
            })
          }
          leafs = data
            .filter(item => item.isRoot === false)
            .map(item => {
              return { id: item.id, label: item.indicatorName }
            })
          leafs.forEach(leaf => {
            row = [projectName, orgName, leaf.label, info.creator]
            data.forEach(item => {
              if (item.id === leaf.id) {
                row.push(this.shwoFriendly(item.scoreValue))
              }
            })
            row.push(this.shwoFriendly(info.score))
            this.formData.push(row)
          })
          const indexs = [0, 1, 3, 5]
          indexs.forEach(index => {
            this.mergeCells.push({
              row: start,
              col: index,
              rowspan: leafs.length,
              colspan: 1
            })
          })
          start = start + leafs.length
        })
      }
      this.$nextTick(() => (this.loading = false))
    },
    //搜索
    searchValueSet() {
      const { name, org, sortType } = this.searchForm
      const filterData = this.networkData.filter(item => {
        let isName = true
        let isOrg = true
        const raw = JSON.parse(item.raw)
        if (name) {
          isName = raw.evaluationTargetTitle === name
        }
        if (org) {
          isOrg = raw.evaluationTargetOrg === org
        }
        return isName && isOrg
      })
      this.convertData(filterData, true, sortType)
    },
    resetAndSearchValueSet() {
      this.$refs['searchForm'].resetFields()
      this.searchValueSet()
    }
  },
  changeData(s) {
    if (typeof ArrayBuffer !== 'undefined') {
      let buf = new ArrayBuffer(s.length)
      let view = new Uint8Array(buf)
      for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
      return buf
    } else {
      let buf = new Array(s.length)
      for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff
      return buf
    }
  },
  async created() {
    if (this.orgList.length <= 0) {
      await this.$store.dispatch('getOrgList')
    }
    this.dealTreeData(this.orgList)
    this.getData()
  }
}
</script>
<style lang="less" scoped>
// 只读单元格样式
/deep/.hot_table {
  .handsontable {
    font-size: 16px;
    color: #000;
    font-weight: 600;
  }
  .handsontable .htDimmed {
    color: #777;
    // background: #eee;
  }
  .header {
    height: 40px;
    line-height: 40px;
  }
}
</style>
